package cn.yuanqiao.web.controller.archive.bianyan;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantYqda;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaDocumentMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.bianyan.domain.SourceMaterial;
import cn.yuanqiao.archive.bianyan.domain.YqDataGerenKu;
import cn.yuanqiao.archive.bianyan.service.IYqDataGerenKuService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.core.context.ResponseUtils;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.bianyan.domain.SpecialSubjectContenr;
import cn.yuanqiao.archive.bianyan.service.ISpecialSubjectContenrService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 专题统稿内容Controller
 *
 * @author xy
 * @date 2023-09-13
 */
@RestController
@RequestMapping("/archive/specialSubjectContenr")
public class SpecialSubjectContenrController extends BaseController
{

    @Autowired
    private ISpecialSubjectContenrService specialSubjectContenrService;

    @Autowired
    private IYqDataGerenKuService yqDataGerenKuService;

    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private TenantYqdaDocumentMapper documentMapper;
    /**
     * 查询专题统稿内容列表
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:SpecialSubjectContenr:list")
*/
    @GetMapping("/list")
    public TableDataInfo list(SpecialSubjectContenr specialSubjectContenr)
    {
        startPage();
        List<SpecialSubjectContenr> list = specialSubjectContenrService.selectSpecialSubjectContenrList(specialSubjectContenr);
        return getDataTable(list);
    }

    /**
     * 导出专题统稿内容列表
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:SpecialSubjectContenr:export")
*/
    @Log(title = "专题统稿内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SpecialSubjectContenr specialSubjectContenr)
    {
        List<SpecialSubjectContenr> list = specialSubjectContenrService.selectSpecialSubjectContenrList(specialSubjectContenr);
        ExcelUtil<SpecialSubjectContenr> util = new ExcelUtil<SpecialSubjectContenr>(SpecialSubjectContenr.class);
        util.exportExcel(response, list, "专题统稿内容数据");
    }

    /**
     * 获取专题统稿内容详细信息
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:SpecialSubjectContenr:query")
*/
    @GetMapping(value = "/{typeId}")
    public AjaxResult getInfo(@PathVariable("typeId") Long typeId)
    {
        return success(specialSubjectContenrService.selectSpecialSubjectContenrById(typeId));
    }

    /**
     * 新增专题统稿内容
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:SpecialSubjectContenr:add")
*/
    @Log(title = "专题统稿内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpecialSubjectContenr specialSubjectContenr)
    {
        return toAjax(specialSubjectContenrService.insertSpecialSubjectContenr(specialSubjectContenr));
    }

    /**
     * 修改专题统稿内容
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:SpecialSubjectContenr:edit")
*/
    @Log(title = "专题统稿内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpecialSubjectContenr specialSubjectContenr)
    {
        return toAjax(specialSubjectContenrService.updateSpecialSubjectContenr(specialSubjectContenr));
    }

    /**
     * 删除专题统稿内容
     */
/*
    @PreAuthorize("@ss.hasPermi('archive:SpecialSubjectContenr:remove")
*/
    @Log(title = "专题统稿内容", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(specialSubjectContenrService.deleteSpecialSubjectContenrByIds(ids));
    }


   /*查看专题下面有没有含有状态不对的数据*/
   @Log(title = "转至成果管理", businessType = BusinessType.INSERT)
   @GetMapping ("/achievement")
   @PreAuthorize("@ss.hasPermi('bianyan:unifiedManuscript:go')")
   public AjaxResult achievement(@RequestParam(value = "ids") Long ids, @RequestParam(value = "mj",required = false)String mj)
   {
       return toAjax(specialSubjectContenrService.achievement(ids,mj));
   }

    /**
     * 获取数据
     */
    @PostMapping("/sourceMaterialList")
    public TableDataInfo sourceMaterialList(@RequestBody SpecialSubjectContenr specialSubjectContenr)
    {
        List<SourceMaterial> list = specialSubjectContenrService.sourceMaterialList(specialSubjectContenr);
        return getDataTable(list);
    }
    /**
     * 获取数据
     */
    @GetMapping("/getSourceMaterialList")
    public TableDataInfo getSourceMaterialList(SpecialSubjectContenr specialSubjectContenr)
    {
        List<SourceMaterial> list = specialSubjectContenrService.getSourceMaterialList(specialSubjectContenr);
        return getDataTable(list);
    }
    //附件预览
    @PostMapping("/view")
    public  ResponseEntity<InputStreamResource> view(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id=request.getParameter("id");
        YqDataGerenKu yqDataGerenKu=yqDataGerenKuService.selectYqDataGerenKuByID(id);
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        if(StringUtils.isEmpty(uplodPath)){
            throw new ServiceException("系统参数错误YQ_ZT_PATH未找到配置！");
        }
        String path=uplodPath+yqDataGerenKu.getFilePath();
        String fileName=yqDataGerenKu.getFileName();
        if (path.equals("null")){
            throw new ServiceException("找不到该附件");
          //  response.sendError(404, "File not found!");
        //    return null;
        }

        // 创建文件输入流
        File file=new File(path);
        FileInputStream fileInputStream = new FileInputStream(file);

        // 创建一个 ResponseEntity 对象
        int lastIndexOfDot = fileName.lastIndexOf('.');
        String fileExtension = fileName.substring(lastIndexOfDot);

        ResponseEntity<InputStreamResource> responseEntity = ResponseEntity
                .ok()
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM) // 根据实际文件类型进行设置
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + new Date().getTime()+fileExtension + "\"")
                .body(new InputStreamResource(fileInputStream));

        return responseEntity;

       /* return responseEntity;
        response.reset(); // 非常重要
        //在线预览，浏览器支持的文件类型都能打开
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=" + fileName);
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(path)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();*/
        /*response.reset(); // 非常重要
        //在线预览，浏览器支持的文件类型都能打开
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "inline; filename=" + fileName);
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(path)));
        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0){
            out.write(buf, 0, len);
        }
        System.gc();
        br.close();
        out.close();*/
    }
    /**
     * 预览
     *
     * @param request
     * @param response docId   文件docid  *
     *                 daId       档案id     daId和categoryId二选一必填
     *                 categoryId  门类id
     * @throws Exception
     */
    @Log(title = "预览", businessType = BusinessType.OTHER)
    @PostMapping("/daView")
    public void daView(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Long doc_id = Long.parseLong(request.getParameter("docId"));
        String daId = String.valueOf(request.getParameter("daId"));
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();
        String efiletable = "";
        if (null == daId || "null".equals(daId)) {
            //tenantCategory.setCategoryId(Long.parseLong(categoryId));
            TenantCategory tenantCategory1 = categoryMapper.selectTenantCategoryByID(Long.parseLong(categoryId), new TenantCategory().getTableName());
            efiletable = tenantCategory1.getEfileTableName();
        } else {
            efiletable = documentMapper.gettablenamebydaid(Long.parseLong(daId), allftable, catetablename);
        }
        TenantYqdaDocument document = specialSubjectContenrService.viewByDocid(doc_id, efiletable);
        String url = document.getDocMnt() + File.separator + document.getPath();
        logger.info(url);
        if (url.equals("null")) {
            response.sendError(404, "File not found!");
            return;
        }
        response.reset(); // 非常重要
        // 设置 CORS 响应头
        ResponseUtils.defaultResponse(response);
        if ("TXT".equals(document.getDocFileType())) {
            readTxtFile(url, document.getDocName(), response);
        } else {
            //在线预览，浏览器支持的文件类型都能打开
            URL u = new URL("file:///" + url);
            //response.setContentType(u.openConnection().getContentType());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + document.getDocName() + "\"");
            //BufferedInputStream br = new BufferedInputStream(new FileInputStream(new File(url)));
            FileInputStream inputStream = null;
            //byte[] buf = new byte[4096];
            //int len = 0;
            //OutputStream out = response.getOutputStream();
            //while ((len = br.read(buf)) > 0){
            //    out.write(buf, 0, len);
            //    out.flush(); // 定期刷新输出流
            // }
            inputStream = new FileInputStream(url);
            int len = 0;
            byte[] buf = new byte[4096];
            OutputStream out = response.getOutputStream();
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
                out.flush(); // 定期刷新输出流
            }
            System.gc();
            inputStream.close();
            out.close();
        }

        /*InputStream inputStream = new FileInputStream(new File(url));
        Reader reader = new InputStreamReader(inputStream, "GBK");
        BufferedReader bufferedReader = new BufferedReader(reader);

        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        String fileContent = stringBuilder.toString();

        // 之后你可以将fileContent作为你的响应内容
        response.setContentType("text/plain; charset=GBK"); // 设置正确的编码格式
        response.setHeader("Content-Disposition", "inline; filename=\"" + document.getDocName() + "\"");
        OutputStream out = response.getOutputStream();
        out.write(fileContent.getBytes("GBK"));

        // 关闭资源
        bufferedReader.close();
        reader.close();
        inputStream.close();*/
    }
    private void readTxtFile(String filePath, String fileName, HttpServletResponse response) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath))) {
            UniversalDetector detector = new UniversalDetector(null);
            byte[] buf = new byte[4096];
            int nread;

            while ((nread = bis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }

            detector.dataEnd();
            //读取txt文件的编码格式
            String encoding = detector.getDetectedCharset();
            detector.reset();
            //以确定的编码格式读取文件
            OutputStream out = response.getOutputStream();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), encoding))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                }
                String fileContent = sb.toString();
                // 之后你可以将fileContent作为你的响应内容
                response.setContentType("text/plain; charset=" + encoding); // 设置正确的编码格式
                response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
                out.write(fileContent.getBytes(encoding));
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
